$(function () {
  let host = 'http://127.0.0.1:5000'
  let gateway = 'http://127.0.0.1:8080'
  $('#select_vale').change(function(){
   
    host = $('#select_vale').val()
  })
  //清除当前页面input数据
  $('#clear_button').click(function() {
    $('input[type="text"]').val('');
  });
  //根据私钥加载账户
  $('#load_waller').click(function(){
    let privatekey = $("#inputLoadPrivateKey").val();
    $.ajax({
        url: gateway + "/loadWalletHandler",
        type: "POST",
        dataType: "json",
        data: JSON.stringify({ privkey: privatekey }),
        contentType: "application/json",
        success: function (response) {
            $("#inputPublic").val(response["public_key"]);
            $("#inputPrivateKey").val(response["private_key"]);
            $("#inputLoadAddress").val(response["blockchain_address"]);
            alert("加载钱包成功！");
            console.info(response);
        },
        error: function (error) {
            console.error(error);
        },
    });
});

  // 随机生成钱包
  $('#wallet_create').click(function(){
    $.ajax({
      url: gateway+"/wallet",
      type: "POST",
      success: function(response){
        $("#inputPublic").val(response["public_key"]);
        $("#inputPrivateKey").val(response["private_key"]);
        $("#inputLoadAddress").val(response["blockchain_address"]);
        alert("随机生成成功！");
        console.info(response);
      },
      error: function(error){
        console.log(error);
      }
    })
  })
  //根据区块编号查询单区块
  $("#SearchByNumber").on("click", function() {
  var blockID = $("#inputBlockNumber").val();
  $.ajax({
    url: host+"/getBlockByNumber", 
    type: "GET",
    dataType: "json",
    data: {
      blockid: blockID
    },
    success: function(response) {
      console.log(response);
      var hashValue = response.hash;
      copyToClipboard(hashValue);
      alert("查询成功：" + JSON.stringify(response) + "\nHash已复制到剪贴板");
    },
    error: function(xhr, status, error) {
      console.error(status + ": " + error);
      alert("查询失败");
    }
  });
});

// 复制文本到剪贴板
function copyToClipboard(text) {
  var tempInput = document.createElement('input');
  tempInput.value = text;
  document.body.appendChild(tempInput);
  tempInput.select();
  document.execCommand('copy');
  document.body.removeChild(tempInput);
}

  //根据区块哈希查询单区块
  $("#SearchByHash").on("click", function() {
    var blockHash = $("#inputBlockHash").val();
    $.ajax({
      url: host + "/getBlockByHash", 
      type: "GET",
      dataType: "json",
      data: {
        hash: blockHash
      },
      success: function(response) {
        console.log(response);
        var previousHashValue = response.previous_hash;
        copyToClipboard(previousHashValue);
        alert("查询成功：" + JSON.stringify(response) + "\nPreviousHash已复制到剪贴板");
      },
      error: function(xhr, status, error) {
        console.error(status + ": " + error);
        alert("查询失败");
      }
    });
  });
  //根据区块交易哈希查询区块
  $("#SearchByPreviousHash").on("click", function() {
    var blockPreviousHash = $("#inputBlockPreviousHash").val();
    $.ajax({
      url: host + "/getBlockByPreviousHash", 
      type: "GET",
      dataType: "json",
      data: {
        previousHash: blockPreviousHash
      },
      success: function(response) {
        console.log(response);
        alert("查询成功：" + JSON.stringify(response));
      },
      error: function(xhr, status, error) {
        console.error(status + ": " + error);
        alert("查询失败");
      }
    });
  });
  //读取历史区块信息
  $(document).ready(function() {
    $("#getBlockContent").click(function() {
      $.ajax({
        url: host+"/readBlockFile",
        type: "POST",
        success: function(response) {
          console.log(response);
          $("#Blockcontent").val(response);
        },
        error: function(error) {
          console.error(error);
        }
      });
    });
  });
  //读取历史交易信息
  $(document).ready(function() {
    $("#getTransactionsContent").click(function() {
      $.ajax({
        url: host+"/readTransactionsFile",
        type: "POST",
        success: function(response) {
          console.log(response);
          $("#Transactionscontent").val(response);
        },
        error: function(error) {
          console.error(error);
        }
      });
    });
  });
  //根据账户地址查询余额
  $('#walletMine_query').click(function(){
    let blockchainAddress = $("#inputAddress").val();
    $.ajax({
        url: host + "/amount",
        type: "POST",
        dataType: "json",
        data: JSON.stringify({ blockchain_address: blockchainAddress }),
        contentType: "application/json",
        success: function (response) {
            alert("查询成功！余额为：" + response.amount);
            console.info(response);
        },
        error: function (error) {
            console.error(error);
        },
    });
  });
  //点击获取当前的账户对象为转账做准备
  $(document).ready(function() {
    $("#wallet_get").click(function() {
      var privateKey = $("#inputPrivateKey").val();
      var publicKey = $("#inputPublic").val();
      var address = $("#inputLoadAddress").val();
  
      var Transactiondata = {
        privateKey: privateKey,
        publicKey: publicKey,
        address: address
      };

      alert("获取成功")
      console.log("账户信息:",Transactiondata);
    });
  });
  //转账功能
  $("#buttonTransaction").click(function(){
    var senderPublicKey =  $("#inputPublic").val();
    var senderPrivateKey = $("#inputPrivateKey").val();
    var senderBlockchainAddress = $("#inputLoadAddress").val();
    var recipientBlockchainAddress = $("#inputReceiveAddress").val();
    var value = $("#inputAmount").val();

    var data = {
      sender_public_key: senderPublicKey,
      sender_private_key: senderPrivateKey,
      sender_blockchain_address: senderBlockchainAddress,
      recipient_blockchain_address: recipientBlockchainAddress,
      value: value
    };
    $.ajax({
      url: gateway + "/transaction",
      type: "POST",
      dataType: "json",
      data: JSON.stringify(data),
      contentType: "application/json",
      success: function (response) {
        alert("转账成功!"+response.message);
        console.info(response);
      },
      error: function (error) {
        console.error(error);
      },
    })
  });
});